package com.eusoft.grades.school;
/**
 * @author Nick Eubanks
 * 
 * Copyright (C) 2010 Android Infinity (http://www.androidinfinity.com)
 *
 */
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;

/**
 * 
 * @author Nick Eubanks
 */
public class Course implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 7972913558556869124L;
	public ArrayList<Category> categories = new ArrayList<Category>();

	public double hours = 0;

	public String ID = "", name = "", section = "", instructor = "",
			email = "", website = "", number = "", location = " ", notes = "";
	public boolean isByPoints;

	public boolean isGraded = true;

	public ArrayList<Date> meetingTimes = new ArrayList<Date>();
	public GradeScale scale = new GradeScale();

	public double calcGradeByPercent() {
		double percent = 0;
		for (Category cat : categories) {
			if (cat.isExtraCredit())
				percent += cat.calculateGrade();
			else
				percent += (cat.calculateGrade() * (cat.weight * .01));
		}

		return percent;
	}

	public double calcGradeByPoints() {
		double extraCredit = 0;
		double earned = 0;
		double worth = 0;

		for (Category cat : categories) {
			PointsObject po = cat.getPointsEarned();
			if (cat.isExtraCredit())
				extraCredit += po.earned;
			else {
				earned += po.earned;
				worth += po.worth;
			}
		}

		if (worth == 0)
			return (earned + extraCredit);
		else
			return ((earned + extraCredit) / worth) * 100;
	}

	/**
	 * Calculates the grade for each category in @categories by
	 * .calculateGrade() and then multiplies that return by the weight for each
	 * category (cat.weight*.01)
	 * 
	 * Returns the sum
	 * 
	 * @return
	 */

	public double calcGradePercent() {
		try {
			if (isByPoints)
				return this.calcGradeByPoints();
			else
				return this.calcGradeByPercent();
		} catch (Exception e) {
			return this.calcGradeByPercent();
		}
	}

	public double calcGradePoints() {
		double courseGrade = this.calcGradePercent();
		int gradeEarned = -1;
		Collections.sort(scale.scale);
		for (Letter l : scale.scale) {
			if (courseGrade >= l.lowerBound)
				gradeEarned++;
		}

		if (gradeEarned != -1)
			return scale.scale.get(gradeEarned).gradePoints;
		else
			return 0;
	}

	public String calcLetterGrade() {
		double courseGrade = this.calcGradePercent();
		int gradeEarned = -1;
		Collections.sort(scale.scale);
		for (Letter l : scale.scale) {
			if (courseGrade >= l.lowerBound)
				gradeEarned++;
		}

		if (gradeEarned != -1)
			return scale.scale.get(gradeEarned).identifier;
		else
			return "F";
	}

}
